package model

import (
	"database/sql"

	"github.com/go-xorm/xorm"
)

// RDERule represents the t_rderule table.
type RDERule struct {
	Name    string         `xorm:"'name'"`
	MaxBorw int            `xorm:"'maxborw'"`
	Startrq sql.NullString `xorm:"'startrq' null"`
	YXDT    int            `xorm:"'yxdt'"`
	QKKJMAX sql.NullInt64  `xorm:"'qkkjmax' null"`
	XJFALG  string         `xorm:"'xjfalg'"`
	YMNY    sql.NullString `xorm:"'ymny' null"`
	ID      string         `xorm:"'id' pk notnull"`
	GBMNY   sql.NullString `xorm:"'gbmny' null"`
	YZMNY   sql.NullString `xorm:"'yzmny' null"`
}

// TableName returns the name of the table in the database.
func (r RDERule) TableName() string {
	return "t_rderule"
}

// GetRDERule retrieves a record by name from the database.
func GetRDERule(engine *xorm.Engine, name string) (*RDERule, error) {
	record := new(RDERule)
	has, err := engine.Where("name = ?", name).Get(record)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, xorm.ErrNotExist
	}
	return record, nil
}

// UpdateRDERule updates a record in the database.
func UpdateRDERule(engine *xorm.Engine, newRecord *RDERule) error {
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	_, err := session.ID(newRecord.Name).Update(newRecord)
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			return rErr
		}
		return err
	}
	if err := session.Commit(); err != nil {
		return err
	}
	return nil
}
